package org.mklink.util;

import org.mklink.enums.Constant;
import org.mklink.enums.ControlEnum;
import javafx.application.Platform;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;

public class MultiThreadFileMover {
    private ExecutorService executor;
    private File topLevelSourceDir; // 保存最顶层的源目录

    /**
     * 文件/目录信息封装类
     */
    private static class FileMoveTask {
        private final File source;
        private final File target;

        public FileMoveTask(File source, File target) {
            this.source = source;
            this.target = target;
        }

        public File getSource() {
            return source;
        }

        public File getTarget() {
            return target;
        }
    }

    /**
     * 多线程移动文件夹及其内容
     * @param sourcePath 源文件夹路径
     * @param targetPath 目标文件夹路径
     * @param threadCount 线程数
     * @param onComplete 任务完成回调
     */
    public void moveDirectory(String sourcePath, String targetPath, Integer threadCount, Runnable onComplete) {
        File sourceDir = new File(sourcePath);
        if (!sourceDir.exists() || !sourceDir.isDirectory()) {
            UI.addListViewItem(ControlEnum.LIST_VIEW_ERROR, LanguageUtil.getString("error.source.not.exist"));
            if (onComplete != null) {
                Platform.runLater(onComplete);
            }
            return;
        }

        // 保存最顶层源目录引用
        topLevelSourceDir = sourceDir;
        
        // 创建目标文件夹
        File targetDir = new File(targetPath);
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }
        if(GlobalThreadPool.getCorePoolSize()!=threadCount){
            GlobalThreadPool.setCorePoolSize(threadCount);
            GlobalThreadPool.setMaximumPoolSize(threadCount);
        }
        // 创建线程池
        executor = GlobalThreadPool.getInstance();
        // 初始化计数器
        AtomicInteger currentTaskCount = new AtomicInteger(0);
        // 在单独的线程中执行移动任务，避免阻塞
        new Thread(() -> {
            try {
                // 先扫描所有需要移动的文件和文件夹
                List<FileMoveTask> tasks = new ArrayList<>();
                scanFiles(sourceDir, targetDir, tasks);
                
                if (!tasks.isEmpty()) {
                    // 使用CountDownLatch跟踪任务完成
                    CountDownLatch latch = new CountDownLatch(tasks.size());

                    // 为每个文件/文件夹分配一个任务
                    for (FileMoveTask task : tasks) {
                        executor.submit(() -> {
                            try {
                                if (task.getSource().isDirectory()) {
                                    // 创建目标目录
                                    task.getTarget().mkdirs();
                                } else {
                                    // 移动文件
                                    moveFile(task.getSource(), task.getTarget());
                                }
                            } catch (Exception e) {
                                UI.addListViewItem(ControlEnum.LIST_VIEW_ERROR, LanguageUtil.getString("error.move.failed") + e.getMessage());
                            } finally {
                                UI.updateLabelText(ControlEnum.LABEL_FILE_SIZE, LanguageUtil.getString("label.log") + tasks.size() + " / " + LanguageUtil.getString("success.file.moved") + currentTaskCount.incrementAndGet());
                                latch.countDown();
                            }
                        });
                    }

                    // 等待所有任务完成
                    try {
                        latch.await();
                        // 删除空的源子目录，但不删除最顶层目录
                        deleteEmptySubdirectories(sourceDir);
                        UI.addListViewItem(ControlEnum.LIST_VIEW_SUCCESS, LanguageUtil.getString(Constant.MV_SUCCESS.getCode()));
                    } catch (InterruptedException e) {
                        UI.addListViewItem(ControlEnum.LIST_VIEW_ERROR, LanguageUtil.getString("error.task.interrupted") + e.getMessage());
                        Thread.currentThread().interrupt();
                    }
                } else {
                    UI.addListViewItem(ControlEnum.LIST_VIEW_SUCCESS, LanguageUtil.getString("success.no.files"));
                }
            } catch (Exception e) {
                UI.addListViewItem(ControlEnum.LIST_VIEW_ERROR, LanguageUtil.getString("error.general") + e.getMessage());
            } finally {
                // 执行完成回调
                if (onComplete != null) {
                    Platform.runLater(onComplete);
                }
            }
        }).start();
    }

    /**
     * 递归扫描所有需要处理的文件和目录
     * @param sourceDir 源目录
     * @param targetDir 目标目录
     * @param tasks 任务列表
     */
    private void scanFiles(File sourceDir, File targetDir, List<FileMoveTask> tasks) {
        File[] files = sourceDir.listFiles();
        
        if (files != null) {
            for (File file : files) {
                File targetFile = new File(targetDir, file.getName());
                tasks.add(new FileMoveTask(file, targetFile));
                UI.updateLabelText(ControlEnum.LABEL_FILE_SIZE, LanguageUtil.getString("label.log") + tasks.size());
                // 如果是目录，递归扫描
                if (file.isDirectory()) {
                    scanFiles(file, targetFile, tasks);
                }
            }
        }
    }
    
    /**
     * 递归删除空的子目录，但不删除最顶层目录
     * @param dir 需要检查的目录
     */
    private void deleteEmptySubdirectories(File dir) {
        if (dir == null || !dir.exists() || !dir.isDirectory()) {
            return;
        }
        // 先递归处理子目录
        File[] files = dir.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteEmptySubdirectories(file);
                }
            }
        }
        
        // 检查当前目录是否为空，且不是最顶层目录，如果是则删除
        files = dir.listFiles();
        if (files != null && files.length == 0 && !dir.equals(topLevelSourceDir)) {
            if (!dir.delete()) {
                UI.addListViewItem(ControlEnum.LIST_VIEW_ERROR, LanguageUtil.getString("error.delete.dir.failed") + dir.getAbsolutePath());
            }else{
                UI.addListViewItem(ControlEnum.LIST_VIEW_SUCCESS, LanguageUtil.getString("success.dir.deleted") + dir.getAbsolutePath());
            }
        }
    }

    /**
     * 移动单个文件
     */
    private void moveFile(File sourceFile, File targetFile) throws IOException {
        Path sourcePath = Paths.get(sourceFile.getAbsolutePath());
        Path targetPath = Paths.get(targetFile.getAbsolutePath());

        // 确保目标文件夹存在
        targetPath.getParent().toFile().mkdirs();

        // 移动文件
        Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);

        UI.addListViewItem(ControlEnum.LIST_VIEW_SUCCESS, LanguageUtil.getString("success.file.moved") + sourceFile.getAbsolutePath());
    }
}
